package com.dzm.xgb.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dzm.common.exception.Assert;
import com.dzm.common.result.ResponseEnum;
import com.dzm.xgb.core.enums.BorrowerStatusEnum;
import com.dzm.xgb.core.enums.IntegralEnum;
import com.dzm.xgb.core.pojo.entity.*;
import com.dzm.xgb.core.mapper.BorrowerMapper;
import com.dzm.xgb.core.pojo.vo.*;
import com.dzm.xgb.core.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 借款人 服务实现类
 * </p>
 *
 * @author Dzm
 * @since 2024-08-27
 */
@Service
public class BorrowerServiceImpl extends ServiceImpl<BorrowerMapper, Borrower> implements BorrowerService {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private BorrowerAttachService borrowerAttachService;

    @Autowired
    private DictService dictService;

    @Autowired
    private UserIntegralService userIntegralService;

    @Autowired
    private IntegralGradeService integralGradeService;

    @Override
    @Transactional(rollbackFor = Exception.class)//对所有异常都回滚
    public void saveBorrowerByUserId(BorrowerVo vo, Long userId) {
        //根据userId查询用户信息
        UserInfo userInfo = userInfoService.getById(userId);

        //构造借款人信息
        Borrower borrower = new Borrower();
        BeanUtils.copyProperties(vo, borrower);
        borrower.setUserId(userId);
        borrower.setName(userInfo.getName());
        borrower.setIdCard(userInfo.getIdCard());
        borrower.setMobile(userInfo.getMobile());
        borrower.setStatus(BorrowerStatusEnum.AUTH_RUN.getStatus());
        //添加借款人信息
        this.save(borrower);

        //修改用户借款状态信息
        userInfo.setBorrowAuthStatus(BorrowerStatusEnum.AUTH_RUN.getStatus());
        userInfoService.updateById(userInfo);

        //添加借款人附件信息
        List<BorrowerAttach> borrowerAttachList = vo.getBorrowerAttachList();
        for (BorrowerAttach borrowerAttach : borrowerAttachList) {
            borrowerAttach.setBorrowerId(borrower.getId());
        }

        borrowerAttachService.saveBatch(borrowerAttachList);

    }

    @Override
    public Integer getBorrowerStatus(Long userId) {
        LambdaQueryWrapper<Borrower> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Borrower::getUserId, userId)
        .orderByDesc(Borrower::getUpdateTime);

        List<Borrower> list = this.list(wrapper);
        if(CollectionUtils.isEmpty(list)) {
            return BorrowerStatusEnum.NO_AUTH.getStatus();
        }

        Borrower borrower = list.get(0);
        return borrower.getStatus();
    }

    @Override
    public Page<Borrower> search(Integer pageNum, Integer pageSize, String keyWords) {
        LambdaQueryWrapper<Borrower> wrapper = new LambdaQueryWrapper<>();
        if(!StringUtils.isEmpty(keyWords)) {
            wrapper.eq(Borrower::getName, keyWords)
                    .or().eq(Borrower::getMobile, keyWords)
                    .or().eq(Borrower::getIdCard, keyWords)
                    .orderByDesc(Borrower::getId);
        }
        Page<Borrower> page = this.page(new Page<>(pageNum, pageSize), wrapper);

        return page;
    }

    /**
     * 根据借款人id查询借款人详细信息
     * @param id
     * @return
     */
    @Override
    public BorrowerDetailVO getDetailVo(Long id) {
        //根据借款人id查询借款对象
        Borrower borrower = this.getById(id);
        //构造详细信息
        BorrowerDetailVO detailVO = new BorrowerDetailVO();
        BeanUtils.copyProperties(borrower, detailVO);

        detailVO.setMarry(borrower.getMarry()?"已婚":"未婚");
        detailVO.setSex(borrower.getSex() == 1? "男" : "女");
        //学历
        String  education = getDictNameByDictCodeAndValue("education", borrower.getEducation().toString());
        detailVO.setEducation(education);
        //行业
        String  industry = getDictNameByDictCodeAndValue("industry", borrower.getIndustry().toString());
        detailVO.setIndustry(industry);
        //月收入
        String  income = getDictNameByDictCodeAndValue("income", borrower.getIncome().toString());
        detailVO.setIncome(income);
        //还款来源
        String  returnSource = getDictNameByDictCodeAndValue("returnSource", borrower.getReturnSource().toString());
        detailVO.setReturnSource(returnSource);
        //关系
        String  relation = getDictNameByDictCodeAndValue("relation", borrower.getContactsRelation().toString());
        detailVO.setContactsRelation(relation);

        //设置审核状态
        detailVO.setStatus(BorrowerStatusEnum.getMsgByStatus(borrower.getStatus()));
        //设置还款人附件信息
        List<BorrowerAttach> list = borrowerAttachService.list(new LambdaQueryWrapper<BorrowerAttach>()
                .eq(BorrowerAttach::getBorrowerId, borrower.getId()));
        List<BorrowerAttachVO> collect = list.stream().map(attach -> {
            BorrowerAttachVO vo = new BorrowerAttachVO();
            vo.setImageType(attach.getImageType());
            vo.setImageUrl(attach.getImageUrl());
            return vo;
        }).collect(Collectors.toList());

        detailVO.setBorrowerAttachVOList(collect);

        return detailVO;
    }

    /**
     * 审批借款人借款信息
     * @param vo
     *
     * 1.修改借款人的状态信息
     * 2.向user_integral表中添加借款详细积分（车辆、身份证、房产）
     * 3.向User_info表中设置用户积分，及审批状态
     *
     */
    @Override
    public void approval(BorrowerApprovalVO vo) {
        //修改借款人
        //获取借款人信息
        Borrower borrower = this.getById(vo.getBorrowerId());
        //修改借款人状态
        borrower.setStatus(vo.getStatus());
        this.updateById(borrower);

        //添加积分
        UserInfo userInfo = userInfoService.getById(borrower.getUserId());
        Integer totalIntegral = userInfo.getIntegral();
        //添加基础积分
        UserIntegral userIntegral = new UserIntegral();
        userIntegral.setUserId(userInfo.getId());
        userIntegral.setContent("借款人基本信息");
        userIntegral.setIntegral(vo.getInfoIntegral());
        userIntegralService.save(userIntegral);
        totalIntegral += userIntegral.getIntegral();
        //车辆积分信息添加
        if(vo.getIsCarOk()) {
            UserIntegral carIntegral = new UserIntegral();
            carIntegral.setIntegral(IntegralEnum.BORROWER_CAR.getIntegral());
            carIntegral.setContent(IntegralEnum.BORROWER_CAR.getMsg());
            carIntegral.setUserId(userInfo.getId());

            totalIntegral += IntegralEnum.BORROWER_CAR.getIntegral();
        }

        //身份证信息添加
        if(vo.getIsIdCardOk()) {
            UserIntegral idCardIntegral = new UserIntegral();
            idCardIntegral.setIntegral(IntegralEnum.BORROWER_IDCARD.getIntegral());
            idCardIntegral.setContent(IntegralEnum.BORROWER_IDCARD.getMsg());
            idCardIntegral.setUserId(userInfo.getId());

            totalIntegral += IntegralEnum.BORROWER_IDCARD.getIntegral();
        }

        //房产积分信息添加
        if(vo.getIsHouseOk()) {
            UserIntegral houseIntegral = new UserIntegral();
            houseIntegral.setIntegral(IntegralEnum.BORROWER_HOUSE.getIntegral());
            houseIntegral.setContent(IntegralEnum.BORROWER_HOUSE.getMsg());
            houseIntegral.setUserId(userInfo.getId());

            totalIntegral += IntegralEnum.BORROWER_HOUSE.getIntegral();
        }

        //修改用户信息
        userInfo.setIntegral(totalIntegral);
        userInfo.setBorrowAuthStatus(vo.getStatus());   //借款状态
        userInfoService.updateById(userInfo);

    }

    @Override
    public BigDecimal getBorrowerAmount(Long userId) {
        //获取登录用户信息
        UserInfo userInfo = userInfoService.getOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getId, userId));
        Assert.notNull(userInfo, ResponseEnum.LOGIN_MOBILE_ERROR);

        //获取用户积分
        Integer integral = userInfo.getIntegral();
        //根据积分查询额度
        IntegralGrade integralGrade = integralGradeService.getOne(new LambdaQueryWrapper<IntegralGrade>()
                .le(IntegralGrade::getIntegralStart, integral)
                .ge(IntegralGrade::getIntegralEnd, integral));
        if(integralGrade == null) {
            return new BigDecimal(0);
        }

        return integralGrade.getBorrowAmount();
    }

    public String getDictNameByDictCodeAndValue(String dictCode, String value) {
        //找到父字典
        Dict parentDict = dictService.getOne(new LambdaQueryWrapper<Dict>()
        .eq(Dict::getDictCode, dictCode));
        Assert.notNull(parentDict, ResponseEnum.SERVLET_ERROR);

        //查询该字典类型所有子字典，且值为value
        Dict one = dictService.getOne(new LambdaQueryWrapper<Dict>()
                .eq(Dict::getParentId, parentDict.getId())
                .eq(Dict::getValue, value));
        Assert.notNull(one, ResponseEnum.SERVLET_ERROR);
        return one.getName();
    }

}
